package org.example.demo1;

public class PC {
    public static void main(String[] args) {
        Number number = new Number();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                try {
                    number.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                try {
                    number.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                try {
                    number.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                try {
                    number.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();


    }
}
class Number{
    private  int number = 0;
    // +
    public synchronized void increment() throws InterruptedException {
        while (number != 0){
            // 等待
            this.wait();
        }
        // 业务
        number++;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        // 唤醒
        this.notifyAll();
    }
    // -
    public synchronized void decrement() throws InterruptedException {
        while (number == 0){
            // 等待
            this.wait();
        }
        // 业务
        number--;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        // 唤醒
        this.notifyAll();
    }
}
